import { Component, OnInit, Input, NgZone } from '@angular/core';

import { MessageService } from 'src/app/shared/service/message.service';

import { Subscription } from 'rxjs';

import { EventService } from 'src/app/shared/service/event.service';

import { AppGlobalService } from '../../shared/service/app-global.service';
import { HttpService } from '../../shared/service/http.service';
@Component({
  selector: 'app-decorate-list',
  templateUrl: './decorate-list.component.html',
  styleUrls: ['./decorate-list.component.scss'],
})
export class DecorateListComponent implements OnInit {
  //   {
  //     "type":"tag",
  //     "style":"decorate_recomme_tag",
  //     "name":null,
  //     "linearLayout":"body",
  //     "data":{
  //         "data":[
  //             {
  //                 "thirdRowLeft":{
  //                     "text":"邻街店铺 | 中式传统 | 200-300m²"
  //                 },
  //                 "firstRowLeft":{
  //                     "imgUrl":"http://zeno-img.oss-cn-shenzhen.aliyuncs.com/file_78450bb103fd60b0ec0ee4f85a33fb6c.jpg",
  //                     "secondTag":{
  //                         "iconUrl":".../png"
  //                     },
  //                     "firstTag":{
  //                         "ifshow":true,
  //                         "label":"推荐"
  //                     },
  //                     "secondTag_2":{
  //                         "name":"我是名字"
  //                     }
  //                 },
  //                 "link":{
  //                     "type":"page",
  //                     "params":{
  //                         "opportunity_id":"5e0feb268dbf8900013f14f1",
  //                         "cuttab":"0",
  //                         "customer_id":"5e0feb258dbf8900013f14f0"
  //                     },
  //                     "target":117249
  //                 },
  //                 "thirdRowRight":{
  //                     "text":"约20万"
  //                 },
  //                 "secondRowLeft":"我是标题"
  //             },
  //             {
  //                 "thirdRowLeft":{
  //                     "text":"邻街店铺 | 中式传统 | 200-300m²"
  //                 },
  //                 "firstRowLeft":{
  //                     "imgUrl":"https://pic8.58cdn.com.cn/p1/big/n_v2ce9158de48a941d19d093c094292de27.jpg;https://pic8.58cdn.com.cn/p1/big/n_v214fdc803f151403c98394d73eacb239b.jpg;https://pic8.58cdn.com.cn/p1/big/n_v294ad143e277944ddaa75077946790e4e.jpg;https://pic8.58cdn.com.cn/p1/big/n_v280cbd94c22a6424cb5547fe091356086.jpg;https://pic8.58cdn.com.cn/p1/big/n_v23e3e0effa0314ef9ab0efbf5d72eb4ad.jpg;https://pic8.58cdn.com.cn/p1/big/n_v2effb061685644191883b66786e2ce2eb.jpg;https://pic8.58cdn.com.cn/p1/big/n_v2e406d1c441ea49adaf2e35457275e97d.jpg",
  //                     "secondTag":{
  //                         "iconUrl":".../png"
  //                     },
  //                     "firstTag":{
  //                         "ifshow":true,
  //                         "label":"推荐"
  //                     },
  //                     "secondTag_2":{
  //                         "name":"我是名字"
  //                     }
  //                 },
  //                 "link":{
  //                     "type":"page",
  //                     "params":{
  //                         "opportunity_id":"5e05bb32a35a7b00014d875e",
  //                         "cuttab":"0",
  //                         "customer_id":"5e05bb31a35a7b00014d875d"
  //                     },
  //                     "target":117249
  //                 },
  //                 "thirdRowRight":{
  //                     "text":"约20万"
  //                 },
  //                 "secondRowLeft":"我是标题"
  //             }
  //         ],
  //         "submit":{
  //             "content":{
  //                 "business_plugin_id":"1,2",
  //                 "pageNo":1
  //             },
  //             "id":"0bea0756-e6f9-4729-bc91-7fb5b6c447da"
  //         }
  //     },
  //     "pageSize":2,
  //     "pageNo":1,
  //     "pageTotal":4
  // }

  @Input() tagData: any;
  pageTotal: 0;
  pageSize: 0;
  pageNo: any = 1;
  params: any;
  defaultImgUrl = "../../assets/img/375x250@2x.png";
  defaultAvatar = '../../assets/img/head.png';
  keyword: any;
  // 声明订阅对象
  subscription: Subscription = null;
  constructor(
    private appGlobalService: AppGlobalService,
    private message: MessageService,
    private http: HttpService,
    private ngZone: NgZone,
    private eventService: EventService
  ) {
  }

  ngOnInit() {
    this.params = this.tagData.data.submit;
    this.pageNo = this.tagData.pageNo;
    this.pageSize = this.tagData.pageSize;
    this.pageTotal = this.tagData.pageTotal;
    const len = this.tagData.data.data.length;
    if (this.tagData.data.submit && this.tagData.data.data.length === 0 && this.tagData.searchText) {
      this.keyword = Object.values(JSON.parse(this.tagData.searchText) )[0];
  }
    if (len > 0) {
      for (let i = 0; i < len; i++) {
        const v = this.tagData.data.data[i];
        if (v.images && v.images.imageUrl !== undefined && (v.images.imageUrl + '').startsWith('http')) {
          let url = v.images.imageUrl ;
          url = url.replace(';', '');
          v.images.imageUrl = url;
        }
        this.tagData.data.data[i] = v;
      }
    }
    const that = this;
    if (!this.subscription && this.tagData.name && this.tagData.name === 'decorate_recomme_tag-filter') {
      this.subscription = this.message.getMessage().subscribe(param => {
        console.log('msg-----> getMessage() ==========' + new Date().toLocaleTimeString());
        // this.message.clearMessage();
        this.tagData.data.data = [];
        // // 重置当前页数
        this.pageNo = 1;
        // 参数
        if (!param) {
          return;
        }
        if (!localStorage.getItem('siftReqConditionTag')) {
          return;
        }
        const siftReqCondition = JSON.parse(localStorage.getItem('siftReqConditionTag'));
        that.postByParam(siftReqCondition);
        // localStorage.removeItem('siftReqConditionTag');
        // this.message.clearMessage();
      });
    }
  }


  // 发送请求更新UI
  postByParam(param) {
    this.tagData.data.data = null;
    this.params.content = param;
    // // 页面数据参数
    this.params.content.pageNo = this.pageNo;
    this.params.sessionId = localStorage.getItem('sessionId');
    // setTimeout(() => {
    //   this.ngZone.runOutsideAngular(() => {
    //     this.ngZone.run(() => {
    // 请求获取新数据
    this.http.post('application/submit', this.params, res => {
      // 请求数据成功
      if (res.success) {
        const result = res.data.data; // JSON.parse(res.data.data);
        // 筛选数据
        this.ngZone.run(() => {
          this.tagData.data.data = result;
        });
        // this.tagData.data.data = null;
        // this.tagData.data.data = result;
        // that.updateDataSource(result);
        // this["tagData"]["data"]["data"] = result;
        // tslint:disable-next-line:no-string-literal
        // that.tagData["data"]["data"] = result;
        // this.tagData.data.data = result;

        // that.tagData.data.data = [];
        // this.tagData.data.data.forEach(element => {
        //     if (this.clickedOpp && this.clickedOpp.indexOf(element.link.params.opportunity_id) > -1) {
        //         element.clicked = true;
        //     }
        // });
      } else {
        // 请求数据失败
        this.appGlobalService.showToast(res.message, 2000, 'middle');
      }
    },
      err => {
        // 请求数据失败
        this.appGlobalService.showToast(err.message, 2000, 'middle');
      });
    //     });
    //   });
    // }, 500);

  }





  get(obj) {
    if (obj.type === "url") {
      this.appGlobalService.openUrl(null, obj.target);
    } else {
      const params = {
        pageId: obj.target,
        params: obj.params,
        sessionId: localStorage.getItem('sessionId')
      };
      this.appGlobalService.goToForward(params);
    }
  }




  loadMoreData(event) {
    setTimeout(() => {
      this.params.sessionId = localStorage.getItem('sessionId');
      // 请求下一个页面
      this.pageNo = this.pageNo + 1;
      this.params.content.pageNo = this.pageNo;
      // 请求获取新数据
      this.http.post('application/submit', this.params, res => {
        // 请求数据成功
        if (res.success) {
          // 追加返回数据
          if (Array.isArray(res.data.data) && res.data.data.length > 0) {
            // 追加数据
            res.data.data.map(item => {
              this.tagData.data.data.push(item);
            });
            // this.params = res.data.submit;
          } else {
            // 没有数据了
            // this.appGlobalService.showToast('没有数据了...', 1000, 'bottom');
          }
          event.target.complete();
        } else {
          // 请求失败，更新当前页数
          this.pageNo = this.pageNo - 1;
          // 请求数据失败
          this.appGlobalService.showToast(res.message, 2000, 'middle');
          event.target.complete();
        }
      });
    }, 500);
  }

  getNgStyle(str) {
    try {
      return JSON.parse(str);
    } catch (error) {
      return {};
    }
  }

  // tslint:disable-next-line:use-life-cycle-interface
  ngOnDestroy(): void {
    try {
      if (this.tagData.data.submit !== undefined) {
        // 组件生命周期结束的时候，注销
        this.subscription.unsubscribe();
      }
    } catch (error) {
    }
  }
  moreActionClick(obj) {
    this.eventService.eventEmit.emit('searchTabListener', obj);
  }
}
